<template>
    <div class="ml-16px mr-16px content-container">
        <div class="pl-26px pt-26px pr-26px pb-16px">
            <div class="flex justify-between cross-center">
                <div class="flex items-center mb-16px">
                    <el-upload class="mr-16px upload-demo" :show-file-list="false" action="#" :http-request="uploadXlsx"
                        :on-success="handleXlsxSuccess">
                        <el-button type="primary"><svg-icon size="18px" icon-class="import-line"
                                class="mr-4px"></svg-icon>导入Excel</el-button>
                    </el-upload>
                    <div class="flex items-center text-14px warning-text-tips"><svg-icon size="16px"
                            icon-class="error-warning-fill"></svg-icon>导入数据后，自动清空之前问题数据和排名数据，慎重操作！</div>
                </div>
                <el-button color="#626aef" @click="handleGenerateOneArticle" v-if="state.oneArticleBtn === 1"><svg-icon size="18px"
                        icon-class="article-line" class="mr-4px"></svg-icon>一键生成1篇文章</el-button>
            </div>
            <Question :tableData="state.tableData" :page="state.page" @update:data="handleUpdateData" v-if="state.row > 0" />
            <Question2Row :tableData="tableDataRows" :page="state.page" @update:data="handleUpdateData" v-else />
        </div>
    </div>
</template>

<script setup lang="ts">
import Question from './components/Question.vue'
import Question2Row from './components/Question2Row.vue'
import { getKeywordListApi, createArticleApi } from '@/api/geo'
import { IDistQuestionItem } from '@/api/geo/types'
import { useHead } from '@vueuse/head'
import type { UploadProps } from 'element-plus'
import axios from 'axios'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { SuccessFilled } from '@element-plus/icons-vue'

const token = sessionStorage.getItem('X-token')

const state = reactive({
    tableData: <IDistQuestionItem[]>[],
    page: {
        total: 0,
        curPage: 1,
        limit: 20,
        pageSizes: 20,
    },
    isLoading: true,
    row:1,
    oneArticleBtn:0
})

// 将数据转换为每行显示两条数据的格式
const tableDataRows = computed(() => {
    const rows = []
    // 计算当前页的起始索引
    const startIndex = (state.page.curPage - 1) * state.page.limit
    for (let i = 0; i < state.tableData.length; i += 2) {
        // 添加 startIndex 以确保 index 是全局连续的
        state.tableData[i].index = startIndex + i + 1
        const item1 = state.tableData[i]
        const item2 = i + 1 < state.tableData.length ? state.tableData[i + 1] : null as any
        if (item2) {
            item2.index = startIndex + i + 2
        }
        rows.push({ item1, item2 })
    }
    return rows
})


function handleUpdateData(value: any) {
    state.page.curPage = value.curPage
    state.page.pageSizes = value.pageSizes
    state.page.limit = value.limit
    getKeywordList()
}

async function getKeywordList() {
    const res: ResType = await getKeywordListApi({
        pn: state.page.curPage,
        pagesize: state.page.pageSizes,
    })
    if (res.code === 200) {
        state.row = res.specifiedPackage
        state.oneArticleBtn = res.specifiedPackage
        state.tableData = res.data
        state.page.curPage = res.page as number
        state.page.pageSizes = res.pagesize as number
        state.page.total = res.count
    }
}

const handleXlsxSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response, uploadFile)
    if (response.code === 200) {
        ElMessage.success(response.message)

    }
}

const uploadXlsx = (options: any): Promise<XMLHttpRequest> => {
    try {
        const formData = new FormData();
        formData.append('file', options.file);

        // 设置请求头
        const config = {
            headers: {
                'Authorization': token,
                'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }
        };

        // 使用 axios 发送请求
        return new Promise((resolve, reject) => {
            axios.post('https://omsapi.vh.mtnets.net/api/GEOApi/KeywordsImport', formData, config)
                .then(response => {
                    ElMessage({
                        message: '导入成功',
                        type: 'success',
                    })
                    getKeywordList()
                    resolve(response as unknown as XMLHttpRequest)
                })
                .catch(error => {
                    ElMessage({
                        message: error.message,
                        type: 'error',
                    })
                    reject(error)
                });
        });
    } catch (error: any) {
        ElMessage({
            message: error.response.data.message || '上传失败',
            type: 'error',
        })
        return Promise.reject(error)
    }
};

async function handleGenerateOneArticle() {
    const res: ResType = await createArticleApi({ ID: 0, count: 1, oneclick: 1 })
    if (res.code === 200) {
        getKeywordList()
        confirmMessageBox(SuccessFilled, res.message)
    } else {
        ElMessage.error(res.message)
    }
}

useHead({
    title: 'GEO：引擎之上，生成万象 - 兴旺宝',
})

onMounted(() => {
    getKeywordList()
})
</script>
<style lang="scss" scoped></style>